package com.zh.onlineexam.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zh.onlineexam.dto.TExamRecordDto;
import com.zh.onlineexam.entity.TExamRecord;
import com.zh.onlineexam.entity.TExamWrongRecord;
import com.zh.onlineexam.entity.TInfoTextContent;
import com.zh.onlineexam.entity.User;
import com.zh.onlineexam.mapper.TExamRecordMapper;
import com.zh.onlineexam.mapper.TInfoTextContentMapper;
import com.zh.onlineexam.service.TExamRecordService;
import com.zh.onlineexam.service.TExamWrongRecordService;
import com.zh.onlineexam.service.TInfoTextContentService;
import com.zh.onlineexam.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @className DailyTestController
 * @Description TODO
 * @Auther 29934
 * @Date 2022/8/27 15:43
 * @Version 1.0
 **/
@RestController
@RequestMapping("/dailyTest")
@Slf4j
@RequiredArgsConstructor
public class DailyTestController {

    private final TInfoTextContentService contentService;
    private final TExamRecordService tExamRecordService;
    private final UserService userService;
    private final TExamWrongRecordService tExamWrongRecordService;

    private final TInfoTextContentMapper contentMapper;
    private final TExamRecordMapper tExamRecordMapper;

    @RequestMapping("/listAll/{subjectId}/{level}/{loginId}")
    public List<TInfoTextContent> listTInfoTextContent(@PathVariable Integer subjectId,@PathVariable Integer level,@PathVariable Integer loginId) throws ExecutionException, InterruptedException {
        //TimeInterval timer = DateUtil.timer();
        //List<TInfoTextContent> list = contentMapper.selectRandomContent(subjectId, level);
        ////把筛选出来的记录加入到做题记录表中
        //User one = userService.getOne(new QueryWrapper<User>().eq("id", loginId));
        ////查询t_exam_record本人做题最大标志位
        //TExamRecord record = tExamRecordService.getOne(new QueryWrapper<TExamRecord>()
        //        .eq("exam_user", one.getRealName())
        //        .orderByDesc("flag_bit")
        //        .last("limit 1"));
        //int flagBit;
        //if(ObjectUtil.isEmpty(record)){
        //    flagBit = 1;
        //}else{
        //    flagBit = (record.getFlagBit() + 1);
        //}
        //tExamRecordService.saveExamRecords(list,one,flagBit);
        //log.info("旧方法用时==="+timer.interval());
        //return list;
        CompletableFuture<List<TInfoTextContent>> orgFuture = CompletableFuture.supplyAsync(
                ()->{
                    List<TInfoTextContent> list = contentMapper.selectRandomContent(subjectId, level);
                    return list;
                }
        );
        CompletableFuture thenAcceptFuture = orgFuture.thenAccept((a) -> {
            //把筛选出来的记录加入到做题记录表中
            User one = userService.getOne(new QueryWrapper<User>().eq("id", loginId));
            //查询t_exam_record本人做题最大标志位
            TExamRecord record = tExamRecordService.getOne(new QueryWrapper<TExamRecord>()
                    .eq("exam_user", one.getRealName())
                    .orderByDesc("flag_bit")
                    .last("limit 1"));
            int flagBit;
            if(ObjectUtil.isEmpty(record)){
                flagBit = 1;
            }else{
                flagBit = (record.getFlagBit() + 1);
            }
            tExamRecordService.saveExamRecords(a,one,flagBit);
        });
        return orgFuture.get();
    }

  /**
   *  用户提交后同步是否正确到做题记录表
   *  */
    @RequestMapping("/updateExamRecord")
    //@Async("asyncServiceExecutor")
    public void updateExamRecord(@RequestBody List<Integer> list){
        if(list.size() > 0){
            //把筛选出来的记录加入到做题记录表中
            Object loginId = StpUtil.getLoginId();
            User one = userService.getOne(new QueryWrapper<User>().eq("id", loginId));
            //查询t_exam_record本人做题最大标志位
            TExamRecord record = tExamRecordService.getOne(new QueryWrapper<TExamRecord>()
                    .eq("exam_user", one.getRealName())
                    .orderByDesc("flag_bit").last("limit 1"));
            list.forEach( a -> {
                tExamRecordService.update(new UpdateWrapper<TExamRecord>()
                .eq("t_info_text_content_id",a)
                .eq("flag_bit",record.getFlagBit())
                .set("is_true",0));
            });
            //同步错题到错题记录表
            List<TExamRecord> examRecords = tExamRecordService.list(new QueryWrapper<TExamRecord>()
                    .notIn("t_info_text_content_id",list)
                    .eq("flag_bit", record.getFlagBit()));
            examRecords.forEach( a -> {
                //判断是否已经存在错题记录中，如果存在就不添加
                TExamWrongRecord wrongRecord = tExamWrongRecordService.getOne(new QueryWrapper<TExamWrongRecord>()
                        .eq("t_info_text_content_id", a.getTInfoTextContentId()));
                if(ObjectUtil.isEmpty(wrongRecord)){
                    TExamWrongRecord tExamWrongRecord = new TExamWrongRecord();
                    tExamWrongRecord.setTInfoTextContentId(a.getTInfoTextContentId());
                    tExamWrongRecord.setExamUser(one.getRealName());
                    tExamWrongRecordService.save(tExamWrongRecord);
                }
            });
        }
    }

    /**
     * 用户答题记录
     */
    @RequestMapping("/listExamRecords")
    public List<TExamRecordDto> listExamRecords(@RequestBody(required = false) String realName){
        return tExamRecordMapper.listExamRecords(realName);
    }

    /**
     * 导出做题记录
     * */
    @RequestMapping("/export")
    public void exportExamRecords(HttpServletResponse response, @RequestParam(required = false) String realName) throws IOException {
        List<TExamRecordDto> listExamRecords = tExamRecordMapper.listExamRecords(realName);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("做题记录", "utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), TExamRecordDto.class)
                .autoCloseStream(Boolean.FALSE)
                .sheet("做题记录")
                .doWrite(listExamRecords);
    }
}
